package com.yiduo.outpost.core.model.typehandlers;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yiduo.outpost.core.model.entity.PermissionMapping;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.Arrays;

/**
 * @author yanwen
 */
@MappedJdbcTypes(JdbcType.ARRAY)
@MappedTypes(PermissionMapping[].class)
public class PermissionMappingTypeHandler extends BaseTypeHandler<PermissionMapping[]> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PermissionMapping[] parameter,
                                    JdbcType jdbcType) throws SQLException {
        Connection c = ps.getConnection();
        Array inArray = c.createArrayOf("varchar",
                Arrays.stream(parameter)
                        .map(JSONObject::toJSONString)
                        .toArray());
        ps.setArray(i, inArray);
    }

    @Override
    public PermissionMapping[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parse(rs.getArray(columnName));
    }

    private PermissionMapping[] parse(Array array) throws SQLException {
        if (array == null) {
            return new PermissionMapping[0];
        }
        String[] resArr = (String[]) array.getArray();
        return Arrays.stream(resArr)
                .map(string -> JSON.parseObject(string, PermissionMapping.class))
                .toArray(PermissionMapping[]::new);
    }

    @Override
    public PermissionMapping[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parse(rs.getArray(columnIndex));
    }

    @Override
    public PermissionMapping[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parse(cs.getArray(columnIndex));
    }
}
